﻿package idv.cjcat.emitter.behaviors {
	use namespace engine;
	
	import idv.cjcat.emitter.*;
	
	/**
	 * Behavior trigger triggered by particle life.
	 */
	public class LifeTrigger extends BehaviorTrigger {
		
		/**
		 * Lower bound.
		 */
		public var lowerBound:Number;
		/**
		 * Upper bound.
		 */
		public var upperBound:Number;
		/**
		 * Behavior trigger triggered interval.
		 */
		public var triggerEvery:int = 1;
		/**
		 * Whether the behavior trigger is triggered when the particle life is within the range form by the two bounds.
		 * <p>
		 * If set to false, the behavior trigger is triggered when the particle life is outside of the range.
		 * </p>
		 */
		public var triggerWithinRange:Boolean;
		
		public function LifeTrigger(lowerBound:Number = 0, upperBound:Number = Number.MAX_VALUE, triggerEvery:int = 1, triggerWithinRange:Boolean = true) {
			this.lowerBound = lowerBound;
			this.upperBound = upperBound;
			this.triggerEvery = triggerEvery;
			this.triggerWithinRange = triggerWithinRange;
		}
		
		override public function test(pd:ParticleData):Boolean {
			if (triggerWithinRange) {
				if ((pd.life >= lowerBound) && (pd.life <= upperBound)) {
					if (pd.life % triggerEvery < 1) return true;
				}
			} else {
				if ((pd.life < lowerBound) || (pd.life > upperBound)) {
					if (pd.life % triggerEvery < 1) return true;
				}
			}
			return false;
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		override public function toXML():XML {
			var xml:XML = super.toXML();
			xml.@type = BehaviorTriggerType.LIFE;
			xml.@lowerBound = lowerBound.toString();
			xml.@upperBound = upperBound.toString();
			xml.@triggerEvery = triggerEvery.toString();
			xml.@triggerWithinRange = triggerWithinRange.toString();
			
			return xml;
		}
		override public function parseXML(xml:XML):void {
			super.parseXML(xml);
			
			lowerBound = parseFloat(xml.@lowerBound);
			upperBound = parseFloat(xml.@upperBound);
			triggerEvery = parseFloat(xml.@triggerEvery);
			triggerWithinRange = (xml.@triggerWithinRange == "true");
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
}